<?php

	header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

	require("frmCookie.php");
	
	$iOpcion = $_GET[iOpcion];
	$iMensaje = $_GET[iMensaje];
	
	if(isset($_REQUEST['producto']))
	{
		$idProducto = $_REQUEST['producto'];
	}
	else
	{
		//Cuando entra desde el menu, no le pasa Producto en la URL por eso predetermino el Producto 2, que son los Celulares
		$idProducto = 2;	
	}
	
	switch ($iMensaje)
	{
		case 1:
		{
			$mensaje = "El movimiento se registro con éxito.";
			break;
		}
	}
	
	switch($iOpcion)
	{
		case 3:
		{
			$consultas = array();
			$mySQL = "SELECT S.idStock FROM stock S, partes P WHERE S.idParte = P.idParte AND S.idAlmacen=" . $_POST[txtOrigenDef];
			$result = readSQL($mySQL);

            foreach($result as $value)
            {
            	$field = "txt" . $value[0] . "hasta";	
            	
            	if($_POST[$field] != "")
            	{
            		$mySQLStock = "SELECT * FROM stock WHERE idStock=" . $value[0];
            		$resultStock = readSQL($mySQLStock);
            		
            		foreach($resultStock as $valueStock)
            		{
            			//echo $field . "<br>";
            			$mySQLStockTran = "INSERT INTO stockentransito(idParte, idAlmacen, idMoneda, imei, nroFactura, codigoReferencia, swVersion, hwVersion, precio, cantidad, fecha, idUsuario, nroRemito, simlock) VALUES(";
            			$mySQLStockTran = $mySQLStockTran . $valueStock['idParte'] . ", ";
            			$mySQLStockTran = $mySQLStockTran . $_POST[txtDestinoDef] . ", ";
            			$mySQLStockTran = $mySQLStockTran . $valueStock['idMoneda'] . ", ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['imei'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['nroFactura'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['codigoReferencia'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['swVersion'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['hwVersion'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['precio'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . $_POST[$field] . ", ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['fecha'] . "', ";
            			$mySQLStockTran = $mySQLStockTran . $_SESSION['idUsuario'] . ", ";
            			$mySQLStockTran = $mySQLStockTran . "'" . $_POST[txtRemitoDef] . "', ";
						$mySQLStockTran = $mySQLStockTran . "'" . $valueStock['simlock'] . "')";
            			//echo $mySQLStockTran . "<br>";
            			array_push($consultas, $mySQLStockTran);
            			//executeSQL($mySQLStockTran);
            			
            			/*$mySQLSelectStock = "SELECT cantidad FROM stock WHERE idStock=" . $value[0];
	            		$resultSelectStock = readSQL($mySQLSelectStock);
						foreach($resultSelectStock as $valueSelectStock)
						{
							$total = $valueSelectStock[0] - $_POST[$field];
							$mySQLUpdateStock = "UPDATE stock SET cantidad = " . $total . " WHERE idStock = " . $value[0];
							echo $mySQLUpdateStock . "<br>";
							executeSQL($mySQLUpdateStock);
						}
						
            			
            			$mySQLMax = "SELECT MAX(idStockEnTransito) FROM stockentransito";
						$resultMax = readSQL($mySQLMax);
						foreach($resultMax as $valueMax)
						{
							$idStockEnTransito = $valueMax[0];
						}
            			
            			$mySQLUsos = "SELECT * FROM tiposusosxstock WHERE idStock=" . $value[0];
	            		$resultUsos = readSQL($mySQLUsos);
	            		foreach($resultUsos as $valueUsos)
	            		{
	            			$mySQLUsosTran = "INSERT INTO tiposusosxstockentransito VALUES(";
	            			$mySQLUsosTran = $mySQLUsosTran . $valueUsos['idTipoUso'] . ", ";
	            			$mySQLUsosTran = $mySQLUsosTran . $idStockEnTransito . ", ";
	            			$mySQLUsosTran = $mySQLUsosTran . $valueUsos['idParte'] . ", ";
	            			$mySQLUsosTran = $mySQLUsosTran . "'" . $valueUsos['imei'] . "', ";
	            			$mySQLUsosTran = $mySQLUsosTran . "'" . $valueUsos['nroFactura'] . "')";
	            			executeSQL($mySQLUsosTran);
	            			echo $mySQLUsosTran . "<br>";
	            		}*/
            		}
            	}
            }
            header("Location: movimientos.php?iOpcion=1&iMensaje=1");
            //echo "SALGO";
            foreach($consultas as $query)
    		{
    			executeSQL($query);
    			//echo $query . "<br>";
    		}
    		//exit;
			break;
		}
	}
?>
<html>
	<head>
    	<?php
		require("frmHeader.php");
		?>
		<script language="javascript" src="scripts/ajax.js"></script>
		<script language="javascript" src="scripts/validar.js"></script>
		<script language="javascript">
			
			var aPartes = new Array();
			
			<?php
			if(($_POST[cboAlmacenOrigen] != "") && ($iOpcion == 2))
			{
				$mySQL = "SELECT S.idStock, P.descripcionFabricante, S.cantidad FROM stock S, partes P WHERE S.idParte = P.idParte AND S.idAlmacen=" . $_POST[cboAlmacenOrigen];
				$result = readSQL($mySQL);
					
				$i = 0;	
	            foreach($result as $value)
	            {
	            	echo "aPartes[$i] = 'txt$value[0]';";
	            	$i++;
	            }
				echo "var pCantidad = $i;";
			}
			?>
			
			var xmlHttp;
			
			function showAlmacenes(inValue, inId)
			{
				xmlHttp = GetXmlHttpObject();
				if (xmlHttp == null)
	  			{
	  				alert ("Your browser does not support AJAX!");
	  				return;
	  			}
				var url = "ajaxOrden.php";
				url = url + "?op=27";
				url = url + "&q=" + inId;
				url = url + "&mod=" + inValue;
				url = url + "&suc=" + <?php echo $_SESSION['idSucursal']; ?>;
				url = url + "&sid=" + Math.random();
				xmlHttp.onreadystatechange = stateChangedAlmacenes;
				xmlHttp.open("GET",url,true);
				xmlHttp.send(null);
			}
			
			function stateChangedAlmacenes() 
			{ 
				if (xmlHttp.readyState == 4)
				{ 
					document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
				}
			}
			
			function GetXmlHttpObject()
			{
				var xmlHttp = null;
				try
	  			{
		 	 		// Firefox, Opera 8.0+, Safari
	  				xmlHttp = new XMLHttpRequest();
	  			}
				catch (e)
	  			{
	  				// Internet Explorer
	  				try
	    			{
	    				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	    			}
	  				catch (e)
	    			{
	    				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	    			}
	  			}
				return xmlHttp;
			}		
			
			function valida(inOp)
			{
				switch(inOp)
				{
					case 1:
					{
						if(frm.cboAlmacenOrigen.options[frm.cboAlmacenOrigen.selectedIndex].text == '')
						{
							alert("Por favor, seleccione el Depósito de Origen.");
							frm.cboAlmacenOrigen.focus();
							return false;
						}
						else if(frm.cboAlmacenDestino.options[frm.cboAlmacenDestino.selectedIndex].text == '')
						{
							alert("Por favor, seleccione el Depósito de Destino.");
							frm.cboAlmacenDestino.focus();
							return false;
						}
						else if(frm.txtNroRemito.value == '')
						{
							alert("Por favor, ingrese el Número de Remito.");
							frm.txtNroRemito.focus();
							return false;
						}
						frm.txtOrigen.value = frm.cboAlmacenOrigen.options[frm.cboAlmacenOrigen.selectedIndex].text;
						frm.txtDestino.value = frm.cboAlmacenDestino.options[frm.cboAlmacenDestino.selectedIndex].text;
						break;
					}
					case 2:
					{
						for(i = 0; i < pCantidad; i++)
						{
							fieldDesde = aPartes[i] + "desde";
							fieldHasta = aPartes[i] + "hasta";
							if(document.getElementById(fieldHasta).value != "")
							{
								if(parseInt(document.getElementById(fieldHasta).value) > parseInt(document.getElementById(fieldDesde).value))
								{
									alert("La cantidad que desea transferir es mayor a la disponible.");
									document.getElementById(fieldHasta).focus();
									return false;
									break;
								}
							}
						}
						break;
					}
					document.frm.submit();
				}
			}
			
			function depositoOrigenChanged()
			{
				xmlHttp = GetXmlHttpObject();
				if (xmlHttp == null)
				{
					alert ("Your browser does not support AJAX!");
					return;
				}
				var url = "ajaxOrden.php";
				url = url + "?op=27";
				url = url + "&q=" + frm.cboAlmacenOrigen.value;
				url = url + "&suc=" + <?php echo $_SESSION['idSucursal']; ?>;
				url = url + "&sid=" + Math.random();
				xmlHttp.onreadystatechange = llenarComboDepositoDestino;
				xmlHttp.open("GET",url,true);
				xmlHttp.send(null);
			}
			
			function llenarComboDepositoDestino() 
			{
				if (xmlHttp.readyState == 4)
				{ 
					if(frm.cboAlmacenDestino != null)
					{
						var almacenes = xmlHttp.responseText.split("||");
						var datosAlmacen;
						var i = 0;
						var indice;
						
						frm.cboAlmacenDestino.options.length = 0;
						
						frm.cboAlmacenDestino.options[0] = new Option("", "");
						
						for(i=0; i<almacenes.length-1; i++)
						{
							datosAlmacen = almacenes[i].split("&&");
							frm.cboAlmacenDestino.options[i+1] = new Option(datosAlmacen[1], datosAlmacen[0]);
							<?php
							if($idAlmacenDestino != "")
							{
							?>
								if(datosAlmacen[0] == <?php echo $idAlmacenDestino;?>)
								{
									indice = i+1;
								}
							<?php
							}
							?>
						}
						
						frm.cboAlmacenDestino.selectedIndex = indice;
					}
				}
			}
			
		</script>
	</head>
	<body>
    	<table cellpadding="0" cellspacing="0" align="center" class="tablaPrincipal">
        	<tr>
            	<td align="center">
                	<?php
					require("frmSession.php"); 
					
					//Redirecciona a SINPERMISOS.PHP en caso de no tener permisos
					switch ($iOpcion)
					{
						case 1:
						case 2:
						{
							
							if (!(in_array(13001, $_SESSION[permisos])))
							{
							?>
							  <script language="JavaScript" type="text/javascript">
							  <!--
							  window.location.href = "sinPermisos.php"
							  //-->
							  </script>
							<?php
							}
							$titulo = "Movimientos de Stock";
							break;
						}
						case 3:
						case 4:
						{
							if (!in_array(13001, $_SESSION[permisos]))
							{
							?>
							  <script language="JavaScript" type="text/javascript">
							  <!--
							  window.location.href = "sinPermisos.php"
							  //-->
							  </script>
							<?php
							}
							$titulo = "Movimientos de Stock";
							break;
						}
						case 5:
						case 6:
						case 7:
						{
							if (!in_array(13001, $_SESSION[permisos]))
							{
							?>
							  <script language="JavaScript" type="text/javascript">
							  <!--
							  window.location.href = "sinPermisos.php"
							  //-->
							  </script>
							<?php
							}
							$titulo = "Movimientos de Stock";
							break;
						}
					}
					
					?>
                </td>
            </tr>
            <tr>
            	<td align="center">
                	<?php
					require("frmTitulo.php");
					?>
                </td>
            </tr>
            <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
            	<td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="menuPrincipal">
                    	<tr>
                        	<td>
								<?php
                                require("frmMenu.php");
                                ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="tituloPantalla">
                    	<tr>
                        	<td align="center">
                            	<p class="texto" align="left"><?php echo $titulo; ?></p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
             <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="estadoPantalla">
                    	<tr>
                        	<td align="center">
                            	<p class="texto" align="left"><?php echo $mensaje; ?></p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
             <tr>
            	<td height="20">&nbsp;
                	
                </td>
            </tr>
            <tr>
                <td align="center">
                	<table cellpadding="0" cellspacing="0" align="center" class="contenedorPrincipal">
                    	<tr>
                        	<td align="">
                        		<?php
                				switch($iOpcion)
                				{
                					case 1:
                					{
        						?>
        						<form name="frm" action="movimientos.php?iOpcion=2" method="post" onsubmit="return valida(1);">
        							<table width="400">
        						<?php
                						break;
                					}
                					case 2:
                					{
            					?>
            					<form name="frm" action="saveDB.php?iOpcion=1" method="post" onSubmit="return valida(2);">
            						<table>
            					<?php	
                						break;
                					}
                				}
        						?>
		                				<?php
		                				switch($iOpcion)
		                				{
		                					case 1:
		                					{
                						?>
                                        <tr>
                                            <td>
                                                *Producto:
                                            </td>
                                            <td>
                                                <select name="producto">
                                                    <?php
                                                    $mySQL = "Select * from productos order by nombre";
                                                    $productos = readSQL($mySQL);
                                                    foreach($productos as $producto)
                                                    {
                                                        if($producto['idProducto'] == $idProducto)
                                                        {
                                                            echo "<option value='".$producto['idProducto']."' selected>".$producto['nombre']."</option>";
                                                        }
                                                        else
                                                        {
                                                            echo "<option value='".$producto['idProducto']."'>".$producto['nombre']."</option>";
                                                            
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </td>
                                        </tr>
                						<tr>
		                					<td width="110">*Deposito de Origen: </td>
		                					<td>
		                						<select name="cboAlmacenOrigen" style="width:100%;" onChange="depositoOrigenChanged();">
		                							<option value=""></option>
			                                       <?php
			    							        $mySQL = "SELECT * FROM almacenes WHERE idSucursal=" . $_SESSION['idSucursal'] . " AND nombre NOT IN('Backoffice BATCH', 'Backoffice BULK', 'Laboratorio BATCH', 'Laboratorio BULK', 'Equipos Terminados Express', 'Equipos Terminados BULK', 'Equipos Terminados BATCH') ORDER BY nombre";
											                    							
			    							        $result = readSQL($mySQL);
			    							
					  				                foreach($result as $value)
					  				                {
				  					                	echo "<option value='" . $value[0] . "'>" . $value['nombre'] . "</option>";
					  				                }
			    							       ?>
			                                      </select>
		                					</td>
		                				</tr>
		                				<tr>
		                					<td>*Deposito de Destino: </td>
		                					<td><select name="cboAlmacenDestino" style="width:100%;"></select>
											</td>
		                				</tr>
                                        <script language="javascript">
											almacenOrigenChanged();
										</script>
		                				<tr>
		                					<td>Nro.Remito:</td>
		                					<td><input type="text" name="txtNroRemito" size="20" maxlength="20" /></td>
		                				</tr>
		                				<tr>
		                					<td colspan="2" align="center"><input type="submit" name="cmdEnviar" value="Continuar"></td>
		                				</tr>
		                				<input type="hidden" name="txtOrigen" value=""/>
		                				<input type="hidden" name="txtDestino" value=""/>
                						<?php
		                						break;
		                					}
		                					case 2:
		                					{
            							?>
            							<tr>
            								<td colspan="3">Deposito de Origen: <b><?php echo $_POST[txtOrigen]; ?></b></td>
            							</tr>
            							<tr>
            								<td colspan="3">Deposito de Destino: <b><?php echo $_POST[txtDestino]; ?></b></td>
            							</tr>
            							<tr>
            								<td colspan="3">Numero de Remito: <b><?php echo $_POST[txtNroRemito]; ?></b></td>
            							</tr>
            							<tr>
            								<td>&nbsp;</td>
            							</tr>
        								<tr>
        									<th class="listaHead">Codigo Tango</th>
        									<th class="listaHead">Parte</th>
        									<th class="listaHead">Imei</th>
        									<th class="listaHead">Cantidad Disponible</th>
        									<th class="listaHead">Cantidad a Transferir</th>
        								</tr>
        								<?php
    									$mySQL = "SELECT S.idStock, S.cantidad, S.imei, P.descripcionFabricante, P.codigoTango FROM stock S, partes P, partesxmodelo PXM, modelos M WHERE M.idProducto = $idProducto AND PXM.idParte = P.idParte AND PXM.idModelo = M.idModelo AND S.cantidad <> 0 AND S.idParte = P.idParte AND S.idAlmacen=" . $_POST[cboAlmacenOrigen]. " group by S.idStock";
										
    									$result = readSQL($mySQL);

			    							
			    						$i = 0;	
		    							
		  				                foreach($result as $value)
		  				                {
	  					                	echo "<tr>";
	  					                	if($i%2==0)
											{
                                        	?>
                                        	<td class="par"><?php echo $value['codigoTango']; ?></td>
                                        	<td class="par"><?php echo $value['descripcionFabricante']; ?></td>
                                        	<td class="par"><?php echo $value['imei']; ?></td>
                                        	<td class="par" align="right"><input type="text" name="txt<?php echo $value['idStock']; ?>desde" value="<?php echo $value['cantidad']; ?>" style="border:none;text-align:right;background:transparent;" size="5" align="right" readonly></td>
                                        	<td class="par" align="right"><input type="text" name="txt<?php echo $value['idStock']; ?>hasta" style="text-align:right;" size="2"></td>
                                        	<?php
											}
											else
											{
											?>
											<td class="impar"><?php echo $value['codigoTango']; ?></td>
											<td class="impar"><?php echo $value['descripcionFabricante']; ?></td>
											<td class="impar"><?php echo $value['imei']; ?></td>
                                        	<td class="impar" align="right"><input type="text" name="txt<?php echo $value['idStock']; ?>desde" value="<?php echo $value['cantidad']; ?>" style="border:none;text-align:right;background:transparent;" size="5" align="right" readonly></td>
                                        	<td class="impar" align="right"><input type="text" name="txt<?php echo $value['idStock']; ?>hasta" style="text-align:right;" size="2"></td>
											<?php
											}
											$i++;
	  					                	echo "</tr>";
		  				                }
        								?>
        								<tr>
        									<td colspan="3" align="center"><input type="submit" name="cmdEnviar" value="Trasferir"></td>
        								</tr>
        								<input type="hidden" name="txtOrigenDef" value="<?php echo $_POST[cboAlmacenOrigen]; ?>"/>
		                				<input type="hidden" name="txtDestinoDef" value="<?php echo $_POST[cboAlmacenDestino]; ?>"/>
		                				<input type="hidden" name="txtRemitoDef" value="<?php echo $_POST[txtNroRemito]; ?>"/>
            							<?php
	                							break;
		                					}
		                				}
		                				?>
		                			</table>
        		            	</form>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
	</body>
</html>